<template>
  <div id="criticalValueQuery">
    <Breadcrumb content="检验质量指标上报" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-form ref="queryFormRef" title-align="right" title-width="60" :data="queryForm">
            <vxe-form-gather span="24">
              <vxe-form-item title="上报日期" field="noticeDate">
                <template #default="{ data }">
                  <vxe-input v-model="data.operateDateStart" placeholder="开始日期" type="date" transfer @change="findQiIndexItemAndDataCollectList"></vxe-input>
                  至
                  <vxe-input v-model="data.operateDateEnd" placeholder="结束日期" type="date" transfer @change="findQiIndexItemAndDataCollectList"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item>
                <template #default>
                  <vxe-button type="text" class="button-blue" content="查询" @click="findQiIndexItemAndDataCollectList"></vxe-button>
                </template>
              </vxe-form-item>
            </vxe-form-gather>
          </vxe-form>
        </template>
      </vxe-toolbar>

      <div class="tableBody">
        <Splitpanes class="area">
          <Pane size="19">
            <vxe-table ref="qiMainTableRef" class="mytable-scrollbar" border align="center" height="auto" :data="mainList" :loading="mLoading" @current-change="clickRowSelect" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true, keyField: 'id' }" :column-config="{ resizable: true }" :tree-config="{
              expandAll: true,
              rowField: 'id'
            }" resizable show-overflow keep-source :reserve="true">
              >
              <vxe-column field="indexName" title="" tree-node align="left"></vxe-column>
            </vxe-table>
          </Pane>
          <Pane size="81">
            <div class="rightTable">
              <vxe-table ref="dataCollectTable" :merge-cells="mergeCells" border show-header-overflow height="auto" show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" :data="collecList" :loading="qloading" class="mytable-scrollbar">
                <!-- <vxe-column type="seq" title="#" width="50"></vxe-column> -->
                <vxe-column field="itemGroup" title="" width="150" align="center">

                </vxe-column>
                <vxe-column field="itemName" title="项目名称" width="400">

                </vxe-column>
                <vxe-column :field="colitem.majorCode" :title="colitem.majorName" v-for="(colitem, index) in majorList" :key="index">
                  <template #default="{ row }">
                    <span>{{ row[colitem.majorCode] }}</span>
                  </template>

                </vxe-column>
              </vxe-table>
            </div>
          </Pane>
        </Splitpanes>
      </div>

    </div>
  </div>
</template>
<script lang="ts" setup>
import Breadcrumb from '@/components/Breadcrumb.vue';
import { reactive, ref, defineExpose, getCurrentInstance, onMounted } from 'vue';
import { IsEmpty, sortByField, formatDateTime } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { Splitpanes, Pane } from 'splitpanes';

import { AppStore } from '@/stores/store';

import { VxeTablePropTypes } from 'vxe-table';

let store = AppStore();
let { proxy }: any = getCurrentInstance();
let sltQiMain: any = reactive({});

let queryForm = reactive({
  operateDateStart: formatDateTime(new Date(), 'yyyy-MM-dd'),
  operateDateEnd: formatDateTime(new Date(), 'yyyy-MM-dd') + ' 23:59:59'
});

let mainList: any = reactive([]); //左侧仪器表格数据
let mLoading = ref(false);
let qloading = ref(false);
let collecList = reactive([]);
let majorList = reactive([]);

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findQiIndexMainAndTypeList(); // 获取左侧仪器表格数据
});

// 获取左侧仪器表格数据
function findQiIndexMainAndTypeList() {
  mainList.length = 0; //放入数据前清空数据
  mLoading.value = true;
  const url = '/api/qi/report/findQiIndexMainAndTypeList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      mainList.push(...res.data);
      if (mainList.length > 0) {
        proxy.$nextTick(() => {
          const $table = proxy.$refs.qiMainTableRef;
          if ($table) {
            $table.setAllTreeExpand(true);
          }
        });

        const sltObj = getChildren(mainList[0]);
        sltQiMain = sltObj;
        setCurTypeNode(sltObj); //定位当前行
        clickRowSelect({ row: sltQiMain }); //点击当前行获取右侧质控项目表格数据
      }
      mLoading.value = false;
    })
    .catch((err: any) => {
      mLoading.value = false;
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}
// 获取children那条数据
function getChildren(obj: any) {
  const children = obj.children;
  return children[0];
}

// 光标定位在左侧仪器表格上
function setCurTypeNode(sltObj: any) {
  proxy.$nextTick(() => {
    const treeName = 'qiMainTableRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentRow(sltObj);
  });
}

// 左侧仪器点击当前行
function clickRowSelect({ row }) {
  const isSearch = row.isSearch;
  if (isSearch == '1') {
    sltQiMain = row;
    findQiIndexItemAndDataCollectList(); // 右侧获取质控项目表格数据
  } else {
    collecList.length = 0;
    sltQiMain = reactive({});
  }
}

// 右侧获取质控项目表格数据
function findQiIndexItemAndDataCollectList() {
  if (IsEmpty(sltQiMain)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    qloading.value = true;
    collecList.length = 0; //放入数据前清空数据
    majorList.length = 0;
    const url = '/api/qi/qiIndexSqlDataCollect/findQiIndexItemAndDataCollectList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          indexId: sltQiMain.id,
          operateDateStart: IsEmpty(queryForm.operateDateStart) ? '' : formatDateTime(queryForm.operateDateStart, 'yyyy-MM-dd') + ' 00:00:00',
          operateDateEnd: IsEmpty(queryForm.operateDateEnd) ? '' : formatDateTime(queryForm.operateDateEnd, 'yyyy-MM-dd') + ' 23:59:59'
        }
      })
      .then((res: any) => {
        majorList.push(...res.data.qiIndexMajorList);
        collecList.push(...res.data.returnList);
        changeCell();
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}

const mergeCells = ref([]);

function mergeRowMethod({ row, _rowIndex, column, visibleData }) {
  const fields = ['itemGroup'];
  const cellValue = row[column.field];

  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  } else if (!IsEmpty(cellValue) && !fields.includes(column.field)) {
    return { row: _rowIndex, col: 0, rowspan: 1, colspan: 2 };
  }
}

function changeCell() {
  const roles = new Set();
  collecList.forEach((shabi) => {
    if (!IsEmpty(shabi.itemGroup)) roles.add(shabi.itemGroup);
  });

  mergeCells.value.length = 0;
  collecList.forEach((shabi, index) => {
    if (IsEmpty(shabi.itemGroup)) {
      shabi.itemGroup = shabi.itemName;
      mergeCells.value.push({ row: index, col: 0, rowspan: 1, colspan: 2 });
    }
  });

  for (let r of roles) {
    let row = collecList.findIndex((a: any) => a.itemGroup == r);
    let count = collecList.filter((item) => item.itemGroup == r).length;
    mergeCells.value.push({ row: row, col: 0, rowspan: count, colspan: 1 });
  }
}
</script>
<style lang="scss" scoped>
#criticalValueQuery {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .vxe-form {
      padding: 5px 10px;

      :deep(.vxe-form--item) {
        margin: 0 10px 0 0;
      }
    }

    .tableBody {
      background-color: $base-white;
      height: calc(100% - 76px);
    }
    .rightTable {
      height: calc(100%);
    }
  }

  .custom-button {
    width: 100%;
    /* 按钮宽度铺满单元格 */
    color: rgb(161, 133, 7);
    /* 字体颜色设置为黄色 */
    background-color: transparent; /* 背景颜色设置为透明 */
    border: none; /* 去除边框 */
    box-shadow: none; /* 去除阴影 */
  }

  .custom-button .el-icon {
    color: rgb(161, 133, 7);
    /* 图标颜色设置为黄色 */
  }

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 0 5px 0 0;
  }

  // 表格最左侧5px间距
  :deep(.vxe-cell) {
    padding-left: 5px;
  }

  :deep(.vxe-form) {
    .vxe-input.type--datetime,
    .vxe-input.type--date {
      width: 150px;
    }

    .el-date-editor {
      height: 24px;
    }

    .el-range-editor.el-input__inner {
      padding: 0;
      width: 320px;
      border-radius: 0;
    }
  }
}
</style>
